package cos.titlegetter;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Pattern;

import cos.entity.Song;

public class ProcessTitleGetter implements TitleGetter {

	private final String PROCESS_STRING = "\\system32\\tasklist.exe /FI \"IMAGENAME eq winamp.exe\" /FO LIST /V";

	private Pattern p = Pattern.compile("Window Title: ");
	private Pattern p1 = Pattern.compile(" - ");
	private Pattern p2 = Pattern.compile("\\. ");

	public Song getCurrentSongTitle() {
		try {
			return parseProcessInput(readProcessInput(loadProcess()));
		} catch (Exception e) {
		}
		return null;
	}

	private Process loadProcess() throws IOException {
		Process process = Runtime.getRuntime().exec(
				System.getenv("windir") + PROCESS_STRING);

		return process;
	}

	private String readProcessInput(Process process) throws IOException {
		StringBuilder sb = new StringBuilder();

		// Get the input stream and read from it
		if (process != null) {
			InputStreamReader in = new InputStreamReader(
					process.getInputStream(), "UTF-8");
			// InputStream in = process.getInputStream();
			int c;
			while ((c = in.read()) != -1) {
				sb.append((char) c);
			}
			in.close();
		}

		return sb.toString();
	}

	/**
	 * parse string, trying to ger pure Artist name and Song title
	 */
	private Song parseProcessInput(String line) {
		Song song = null;
		try {
			String[] arr = p1.split(p.split(line, 2)[1], 3);
			song = new Song(p2.split(arr[0])[1], arr[1]);
		} catch (Exception e) {
			return null;
		}
		return song;
	}
}
